<template>
	<div id="setActivity" 
		v-loading="fetchLoading"
		element-loading-text="拼命加载中..">
		<div class="content-box">
			<div class="content-title">
				<ul>
					<li><i class="fa fa-check-circle" aria-hidden="true"></i>新建活动</li>
					<li class="linebox"></li>
					<li><i class="fa fa-check-circle" aria-hidden="true"></i>选择模板</li>
					<li class="linebox"></li>
					<li class="active"><i class="fa fa-check-circle" aria-hidden="true"></i>活动设置</li>
				</ul>
			</div>
			<div class="set-box">
				<!-- 左边手机模拟窗口 -->
				<div class="set-left">
					<div class="window-title">{{form.activityName}}</div>
					<div class="window-content" :style="{'background-image': 'url('+showBg+')'}">
						<!-- banner -->
						<div class="window-banner"></div>
						<!-- 输入框 -->
						<!--<div class="window-input window-input1"><input type="text" placeholder="请输入口令"></div>-->
						<!-- 按钮 -->
						<!-- <div class="window-input window-input2">领取奖品</div>-->
						<!-- <div class="question">什么是口令?</div>-->
						<!-- 时间口令 -->
						<!--<div class="time-code-box">
							<div class="time-code-item"
							     v-for="(item, index) in form.timeCodePrizeRuleData"
							     v-show="item.startTime&&item.endTime">
								<div class="time-code-item-box clearfix">
									<div class="left-time-code">00:00</div>
									<div class="right-time-code">
										<p>即将开始</p>
										<span>{{item.startTime}}</span>
									</div>
								</div>
							</div>
						</div>-->
						<!-- 分享弹框 -->
						<div class="window-share-mask" v-show="form.shareSwitch&&currentTab==2">
							<div class="window-share-box">
								<p>{{form.shareTitle}}</p>
								<div>{{form.shareContent}}</div>
								<img :src="form.shareIcon" v-show="form.shareIcon">
							</div>
						</div>
					</div>
				</div>
				<div class="set-right">
					<div class="set-content">
						<div class="set-tab clearfix">
							<div v-for="(item,index) in tabData"
								 class="tab-item"
								 :class="{'active': currentTab == index}"
								 @click="tabClickEvent(index)">{{item}}</div>
						</div>

						<!-- 内容设置 -->
						<div class="tab-content" v-show="currentTab==0">
							<div class="form-item-box clearfix">
								<div class="form-item-left require-item">活动名称:</div>
								<div class="form-item-right">
									<input type="text" maxlength="50" v-model="form.activityName">
								</div>
							</div>
							<div class="form-item-box clearfix">
								<div class="form-item-left require-item">活动时间:</div>
								<div class="form-item-right pick-date-box">
									<el-date-picker
								      v-model="form.startTime"
								      type="datetime"
									  :picker-options="pickerOptions"
								      placeholder="选择开始时间">
								    </el-date-picker><span class="separate-box">至
								    </span><el-date-picker
								      v-model="form.endTime"
								      type="datetime"
									  :picker-options="pickerOptions"
								      placeholder="选择结束时间">
								    </el-date-picker>
								</div>
							</div>
							<div class="form-item-box clearfix">
								<div class="form-item-left require-item">兑换次数:</div>
								<div class="form-item-right lotteryNum-box">
									<span class="separate-box">每人可抽奖
								    </span><input class="input-lottery" type="text" v-model="form.lotteryNum"><el-select v-model="form.tagDetailValue">
									    <el-option
									      v-for="item in lotteryNumOptions"
									      :key="item.value"
									      :label="item.label"
									      :value="item.value">
									    </el-option>
									  </el-select>
								</div>
							</div>
							<div class="form-item-box clearfix">
								<div class="form-item-left">更换背景:</div>
								<div class="form-item-right add-banner">
									<span class="add-banner-btn" 
										  v-show="!form.bgImg"
										  @click="showUploadPicToast(1)">+</span>
									<img v-show="form.bgImg" :src="form.bgImg" />
									<i class="fa fa-times" 
									   aria-hidden="true"
									   v-show="form.bgImg"
									   @click="cancelBg(1)"></i>
									<p>640*1200像素，支持PNG、JPG格式，小于200KB</p>
								</div>
							</div>
							<div class="form-item-box clearfix last-item">
								<div class="form-item-left require-item">口令说明:</div>
								<div class="form-item-right rule-box">
							      	<quill-editor 
							      		  v-model="form.activityRules"
							              ref="myQuillEditor"
							              class="editer"
							              :options="editorOption"
							              @ready="onEditorReady($event)">
									</quill-editor>
								</div>
							</div>
						</div>
						
						<!-- 奖品设置 -->
						<div class="tab-content" v-show="currentTab==1">
							<div class="form-item-box clearfix">
								<div class="form-item-left">口令类型:</div>
								<div class="form-item-right code-type-radio">
									<el-radio-group v-model="form.codeType">
								      <el-radio label="1">固定口令</el-radio>
								      <el-radio label="2">定时口令</el-radio>
								    </el-radio-group>
								</div>
							</div>
							<div class="form-item-box clearfix mb0">
								<div class="form-item-left">中奖规则:</div>
							</div>

							<!-- 固定口令 -->
							<div class="prize-set-box" v-show="form.codeType==1&&currentTab==1">
								<ul class="prize-set-head">
									<li class="prize-list">类型</li> 
									<li class="prize-img">口令</li>
									<li class="prize-name">中奖奖品</li>
									<li class="winning-limit">库存</li>
									<li class="trash"></li>
								</ul>
								<div class="prize-set-content">
									<ul v-for="(item, index) in form.prizeRuleData">
										<li class="prize-list">
											<el-radio-group v-model="item.codeWay">
										      <el-radio label="1">唯一口令</el-radio>
										      <el-radio label="2">随机口令</el-radio>
										    </el-radio-group>
										</li>
										<li class="prize-img prize-img-item">
											<input v-show="item.codeWay==1" v-model="item.writeCode" type="text" placeholder="">
											<div v-show="item.codeWay==2" 
											     class="upload-code"
											     @change="addCsv($event,index)"
											     :class="{'upload-code-done': item.csvFile}">
												<input type="file" accept=".csv" >
											</div>
										</li>
										<li class="prize-name prize-name-item">
											<input type="text" readonly @click="showAddPrizeToast(index,1)" v-model="item.prize">
										</li>
										<li class="winning-limit limit-item">
											<input type="text" v-model="item.restNum" placeholder="请输入库存">
										</li>
										<li class="trash-item">
											<i class="fa fa-trash-o" 
											   aria-hidden="true"
											   v-if="form.prizeRuleData.length>1"
											   @click="deletePrizeRule(index,item)"></i>
										</li>
									</ul>
								</div>
							</div>
							<!--<div class="prize-set-footer" v-show="form.codeType=='1'"><i class="fa fa-info-circle exclamatory" aria-hidden="true"></i>本模板添加奖品数量<span>1</span> ～ <span>50</span>个。
								<div class="footer-btn"
								     @click="addPrizeRule">添加奖品</div>-->
							</div>
							<div class="prize-set-footer csv-footer" v-show="form.codeType=='1'">提示：口令文件需要CSV格式,每次最多导入10000条记录。下载 [<a href="./../../static/lib/file/口令示例.csv">示例</a>]</div>

							<!-- 定时口令 -->
							<div class="prize-set-box" v-show="form.codeType==2&&currentTab==1">
								<ul class="prize-set-head">
									<li class="_prize-list">开启时间</li>
									<li class="_prize-img">口令</li>
									<li class="_prize-name">中奖奖品</li>
									<li class="_winning-limit">库存</li>
									<li class="_trash"></li>
								</ul>
								<div class="prize-set-content">
									<ul v-for="(item, index) in form.timeCodePrizeRuleData">
										<li class="_prize-list prize-img-item">
											<el-date-picker
										      v-model="item.startTime"
										      format="yyyy-MM-dd HH:mm"
										      value-format="yyyy.MM.dd"
											  :picker-options="pickerOptions"
											  placeholder="开始时间"
										      type="datetime">
										    </el-date-picker><span class="separate-box">至
										    </span><el-date-picker
										      v-model="item.endTime"
										      type="datetime"
											  :picker-options="pickerOptions"
											  placeholder="结束时间"
										      format="yyyy-MM-dd HH:mm"
										      value-format="yyyy.MM.dd">
										    </el-date-picker>
										</li>
										<li class="_prize-img prize-img-item">
											<input type="text" placeholder="" v-model="item.code">
										</li>
										<li class="_prize-name prize-name-item">
											<input type="text" readonly @click="showAddPrizeToast(index,2)" v-model="item.prize">
										</li>
										<li class="_winning-limit limit-item">
											<input type="text" v-model="item.restNum" placeholder="0">
										</li>
										<li class="_trash trash-item">
											<i class="fa fa-trash-o" 
											   aria-hidden="true"
											   @click="deleteTimeCodePrizeRule(index,item)"></i>
										</li>
									</ul>
								</div>
								<div class="prize-set-footer add-time">
									<!--<i class="fa fa-plus-circle" 
									   aria-hidden="true"
									   @click="addTimeCode"></i>最多可以添加3个时段</div>-->
							</div>
						</div>

						<!-- 拉新设置 -->
						<div class="tab-content" v-show="currentTab==2">
						<!-- 发布到APP -->
							<div class="form-item-box clearfix">
								<div class="form-item-left code-left title-channel">发布到APP:</div>
								<div class="form-item-right code-switch">
									<el-switch
									  v-model="form.implantApp"
									  active-color="#64bd63"
									  inactive-color="#ffffff">
									</el-switch>
								</div>
							</div>
							<div class="form-item-box clearfix" v-show="form.implantApp">
								<div class="form-item-left require-item">APP下载链接:</div>
								<div class="form-item-right">
									<input type="text" v-model="form.appDownloadUrl">
								</div>
							</div>
							<div class="form-item-box clearfix">
								<div class="form-item-left code-left">发布到微信:</div>
									<div class="form-item-right code-switch">
										<el-switch
										v-model="form.codeSwitch"
										active-color="#64bd63"
										inactive-color="#ffffff">
										</el-switch>
									</div>
								</div>
								<div class="form-item-box clearfix" v-show="form.codeSwitch">
									<div class="form-item-left code-left">上传二维码:</div>
									<div class="form-item-right add-banner">
										<span class="add-banner-btn"
											v-show="!form.qrcode"
											@click="showUploadPicToast(2)">+</span>
										<img v-show="form.qrcode" :src="form.qrcode" />
										<i class="fa fa-times" 
										aria-hidden="true"
										v-show="form.qrcode"
										@click="cancelBg(2)"></i>
										<p>上传1:1图片，支持PNG、JPG格式，小于20KB</p>
									</div>
								</div>
							<div class="form-item-box clearfix">
								<div class="form-item-left">开启分享:</div>
								<div class="form-item-right ">
									<el-switch
									  v-model="form.shareSwitch"
									  active-color="#64bd63"
									  inactive-color="#ffffff">
									</el-switch>
								</div>
							</div>
							<div v-show="form.shareSwitch">
								<div class="form-item-box clearfix">
									<div class="form-item-left require-item">分享图标:</div>
									<div class="form-item-right add-banner">
										<span class="add-banner-btn"
											v-show="!form.shareIcon"
											@click="showUploadPicToast(3)">+</span>
										<img v-show="form.shareIcon" :src="form.shareIcon" />
										<i class="fa fa-times" 
										aria-hidden="true"
										v-show="form.shareIcon"
										@click="cancelBg(3)"></i>
										<p>上传1:1图片，支持PNG、JPG格式，小于20KB</p>
									</div>
								</div>
								<div class="form-item-box clearfix">
									<div class="form-item-left require-item">分享标题:</div>
									<div class="form-item-right">
										<input type="text" v-model="form.shareTitle" placeholder="最多32个字">
									</div>
								</div>
								<div class="form-item-box clearfix">
									<div class="form-item-left require-item">分享文案:</div>
									<div class="form-item-right textarea-box">
										<textarea placeholder="最多50个字" v-model="form.shareContent"></textarea>
									</div>
								</div>
								<!--<div class="form-item-box clearfix">
									<div class="form-item-left">被分享者:</div>
									<div class="form-item-right use-info-box">
										引导被分享者关注二维码后参与<span>使用说明</span>
									</div>
								</div>-->
							</div>
							
							
						</div>

						<!-- 信息备注 -->
						<div class="tab-content" v-show="currentTab==3">
							<h6>只供商家做相关活动信息的备注，不显示在用户界面上</h6>
							<div class="form-item-box clearfix">
								<div class="form-item-left">活动ID:</div>
								<div class="form-item-right">
									<input type="text" v-model="form.activityInfoId">
								</div>
							</div>
							<div class="form-item-box clearfix">
								<div class="form-item-left">组织方:</div>
								<div class="form-item-right">
									<input type="text" v-model="form.organizerInfo">
								</div>
							</div>
							<div class="form-item-box clearfix">
								<div class="form-item-left">活动备注:</div>
								<div class="form-item-right textarea-box textarea-note-box">
									<textarea v-model="form.activityInfoNote"></textarea>
								</div>
							</div>
							<div class="form-item-box clearfix">
								<div class="form-item-left">其他:</div>
								<div class="form-item-right textarea-box textarea-note-box">
									<textarea v-model="form.activityInfoRests"></textarea>
								</div>
							</div>
						</div>

						<!-- 列表配置 -->
						<div class="tab-content clear-both" v-show="currentTab==4">
							<h6>列表配置仅限使用列表模式使用，如不需要使用列表模式请忽略此设置</h6>
							<div class="form-item-left">列表缩略图:</div>
							<div class="form-item-right add-banner">
								<span class="add-banner-btn"
									v-show="!form.listThumbnailIcon"
									@click="showUploadPicToast(4)">+</span>
								<img v-show="form.listThumbnailIcon" :src="form.listThumbnailIcon" />
								<i class="fa fa-times" 
								aria-hidden="true"
								v-show="form.listThumbnailIcon"
								@click="cancelBg(4)"></i>
								<p>支持PNG、JPG格式，小于200KB</p>
							</div>
						</div>

						<el-button  class="save-btn" @click="addGuessCode">{{subText}}</el-button>
					</div>
				</div>
			</div>
		</div>



		<!-- 添加奖品弹框 -->
		<div class="add-prize-mask" v-if="addPrizeBox">
			<div id="add-prize-box">
				<div class="add-prize-header">
					<el-input placeholder="请输入奖品名称进行搜索" v-model="availableForm.q">
					    <el-button slot="append" @click.native="searchPriceList"><i class="fa fa-search" aria-hidden="true"></i></el-button>
					</el-input>
					<!--<div class="refresh-btn">刷新</div>-->
					<span class="close" @click="hideAddPrizeToast"></span>
				</div>
				<div class="add-prize-body" style="height: 340px; overflow: auto;">
					<div class="table-header">
						<table>
							<thead>
								<tr>
									<td>奖品名称</td>
									<td>类型</td>
									<td>有效期</td>
									<td>可用/库存</td>
									<td>操作</td>
								</tr>
							</thead>
						</table>
					</div>
					<div class="table-body">
						<table v-if="prizeList.length!=0">
							<tbody>
								<tr v-for="(item,index) in prizeList" v-show="item.availables>0">
									<td>{{item.name}}</td>
									<td>{{item.type_code | typeCode}}</td>
									<td>{{item.expired_start }}<br/>{{item.expired_end }}</td>
									<td>{{item.availables}}</td>
									<td>
										<div class="pick-btn"
											@click="pickPrize(item,index)">选取</div>
									</td>
								</tr>
							</tbody>						
						</table>
						<div class="text-hit" v-else>暂无数据</div>					
					</div>
				</div>
				<div class="add-prize-footer">
					<div class="page-inner">
						<el-pagination
							small
							layout="prev, pager, next"
							:total="availableForm.total"
							@current-change="selectPrize"
							>
						</el-pagination>
					</div>
				</div>
			</div>
		</div>

		<!-- 上传图片弹框 -->
		<div class="add-prize-mask" v-if="uploadPicBox">
			<div id="upload-pic-box" v-loading="imgUpLoading">
				<div class="add-prize-header">
					上传图片
					<span class="upload-close" @click="hideUploadPicToast"></span>
				</div>
				<div class="upload-body">
					<ul class="clearfix upload-img-list">
						<li><input type="file" 
							       @change='addImgEvent'
							       accept="image/png, image/jpeg, image/jpg">
						</li>
						<!--<li v-for="(item, index) in uploadPicList"
							@click="chooseBannerImg(index)"
							:class="{'border-red': currentBannerIndex===index}"
						    :style="{'background-image': 'url('+item.src+')'}"></li>-->
					</ul>
				</div>
				<div class="add-prize-footer">
					<div class="page-inner upload-page-inner">
						<div style="display:inline-block;">
							<el-pagination
								small
								layout="prev, pager, next"
								:total="updateImgtotal"
								@current-change="pageChange"
								>
							</el-pagination>
						</div>
						<el-button @click="hideUploadPicToast">取消</el-button>
						<el-button type="primary" @click="comfirmBannerImg">确定</el-button>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
	import { quillEditor } from 'vue-quill-editor'
	import { baseImgPath } from './../config/env'
	import * as api from './../api/api';
	import Vue from 'vue'
	export default {
		data(){
			return {
				imgUpLoading:false,  //上传图片loading
				fetchLoading:false,  //页面loading
				pickerOptions: {
					disabledDate(time) {
						return time.getTime() < Date.now() - 8.64e7;
					}
				},
				defaultBg: '',
				form: {
					tplModelId:'',  //模板id
					model_id:'',//模型id
					activityNo:'', //活动id
					//内容设置
					activityName: '',
					bgImg: '',
					bannerImg: '',
					startTime: '',
					endTime: '',
					lotteryNum: 1,
					tagValue: '',
					tagDetailValue: 'all',
					activityRules:'',//口令说明
					//信息备注
					activityInfoId:'', //活动id
					organizerInfo: '',// 活动组织方
					activityInfoNote:'', //活动备注
					activityInfoRests:'', //其他
					//列表配置
					listThumbnailIcon:'',
					//分享
					shareSwitch: false,
					shareTitle: '',
					shareIcon: '',
					shareContent: '',
					//发布到app
					appDownloadUrl:'',
					implantApp:false,
					//开启二维码
					codeSwitch: false,
					qrcode:'',//二维码
					prizeOptionValue: '0',
					//规则设置
					codeType: '1',   //口令类型
					// 固定口令
					prizeRuleData: [ {
						codeWay: '1',
						writeCode:'', //手动填写口令
						code: '',
						csvFile: '',
						csvUrl:'',
						prize: '',  //奖品名称
						id:'',		//奖品id
						availables:'', //可用库存
						restNum: 1,
						list:''
					}],
					//定时口令
					timeCodePrizeRuleData: [ {
						startTime: '',
						endTime: '',
						code: '',
						prize: '',  //奖品名称
						id:'',		//奖品id
						availables:'', //可用库存
						restNum: 1,
						list:''
					}]
				},
				prizeIndex:['一','二','三','四','五','六','七','八','九','十','十一','十二','十三','十四','十五','十六','十七','十八','十九','二十'],
				lotteryNumOptions: [{
		          value: 'all',
		          label: '次/活动全程'
		        },{
		          value: 'day',
		          label: '次/每日'
		        }],

		        prizeOptions: [],
			    editorOption: { },
		        tabData: ['内容设置','规则设置','拉新设置','信息备注','列表配置'],
		        currentTab: 0,
				isTabContentShow:false,  //内容设置是否提交成功,提交成功后开始设置奖品拉新等信息
				// isTabListShow:false, //保存选择的奖品后，开始设置其他选项
				subText:'下一步',  //完成按钮提示文字
		        specialRuleData: [],
		        addPrizeBox: false,
		        pickedPrizeList: [],  //选中的奖品列表
				postNum:null,   //选择的奖品数量
		        prizeList: [],  //所以奖品  实例渲染
				prizeAll:[],  //所以奖品
		        uploadPicList:[{src: require('../assets/img/act_bg.png')}],
		        currentBannerIndex: -1,
		        uploadPicBox: false,  //上传图片box
				uploadImgBoxIndex:null,
		        currentAddPrizeIndex: '',

				//选择奖品分页
				// selectprizecurrent_page:1, //当前页码
                // selectprizelast_page:'',//最后一页
                // selectprizelimit:10, //一页显示多少条
                // selectprizetotal:1, //总条数

				//上传图片分页
				updateImgcurrent_page:1, //当前页码
                updateImglast_page:'',//最后一页
                updateImglimit:10, //一页显示多少条
                updateImgtotal:1, //总条数

				//获得奖品列表
				availableForm:{
					per_page:15,  //一页显示多少条
					last_page:1,    //总共好多页面
					page:1,   //当前第几页
					q:''	//搜索
				},
			}
		},
		watch:{
			currentTab(v,n){
				v==this.tabData.length-1?this.subText='完成':this.subText='下一步'
			},
			pickedPrizeList(v,n){
				this.postNum=this.pickedPrizeList.length;
			},
			'form.codeType'(v,n){
				this.getAvailable();
				this.form.prizeRuleData=[{
					codeWay: '1',
					writeCode:'', //手动填写口令
					code: '',
					csvFile: '',
					csvUrl:'',
					prize: '',  //奖品名称
					id:'',		//奖品id
					availables:'', //可用库存
					restNum: 1,
					list:''
				}];
				this.form.timeCodePrizeRuleData=[{
					startTime: '',
					endTime: '',
					code: '',
					prize: '',  //奖品名称
					id:'',		//奖品id
					availables:'', //可用库存
					restNum: 1,
					list:''
				}];
			}
		},
		mounted(){
			this.getAvailable();//获得奖品列表
		},
		components: {
			quillEditor
		},
        computed: {
          	editor() {
	        	return this.$refs.myQuillEditor.quill;
	      	},
	      	showBg(){
	      		return this.form.bgImg?this.form.bgImg:this.defaultBg;
	      	}
        },
        methods: {
			addGuessCode(){
				let vm = this;
				if(!vm.isTabContentShow&&vm.currentTab==0){
					if(vm.contentSetReg()){
						//背景图
						let bgImg='';
						if(vm.form.bgImg){
							bgImg=vm.form.bgImg;
						}else{
							bgImg=vm.defaultBg;
						}
						let body={
							name:vm.form.activityName,
							category:2,   
							start_time:vm.timeDateMinutes(vm.form.startTime),
							end_time:vm.timeDateMinutes(vm.form.endTime),
							backgroundImg:bgImg,
							model_id:vm.form.model_id,
							template_id:vm.form.tplModelId,
							description:vm.form.activityRules,
							style_rule:{
								backgroundImg:bgImg,
								banner:[]
							},
							limits:{
								type:vm.form.tagDetailValue,     //一天或者全程
								num:vm.form.lotteryNum        //参与次数
							},
						};
						
						api.postGuessCode(body).then(res=>{
							if(res.data.code==200){
								vm.isTabContentShow=true;
								vm.form.activityNo=res.data.data.id;
								vm.currentTab++;
							}	
						}).catch(err=>{
							vm.httpStatusCode(err);
						})	
					}
				
				}else{
					if(vm.currentTab!=vm.tabData.length-1){
						vm.currentTab++;
					}else{
						if(vm.contentSetReg()&&vm.prizeSetReg()&&vm.wxSetReg()&&vm.appSetReg()){
							vm.postActivityCommon();  //保存所有信息
						};
					}	
				}
			},
			//保存所有信息
			postActivityCommon(){
				let vm = this;
				vm.fetchLoading=true;
				let shareIsOpen;   //发布到微信分享 
				vm.form.shareSwitch?shareIsOpen='on':shareIsOpen='off';
				//背景图
				let bgImg='';
				if(vm.form.bgImg){
					bgImg=vm.form.bgImg;
				}else{
					bgImg=vm.defaultBg;
				}
				var body={
					name:vm.form.activityName,
					category:2,   
					start_time:vm.timeDateMinutes(vm.form.startTime),
					end_time:vm.timeDateMinutes(vm.form.endTime),
					backgroundImg:bgImg,
					model_id:vm.form.model_id,
					template_id:vm.form.tplModelId,
					description:vm.form.activityRules,
					style_rule:{
						backgroundImg:bgImg,
						banner:[]
					},
					limits:{
						type:vm.form.tagDetailValue,     //一天或者全程
						num:vm.form.lotteryNum        //参与次数
					},
					//发布到微信 
					shares:{
						isopen:shareIsOpen,
						title:vm.form.shareTitle,
						content:vm.form.shareContent,
						thumb:vm.form.shareIcon
					}, 
					listBackgroundImg:vm.form.listThumbnailIcon, //  列表配置
					customId: vm.form.activityInfoId,// 自定义id
					organizer: vm.form.organizerInfo,//   组织方
					remark:  vm.form.activityInfoNote,//   备注
					others:  vm.form.activityInfoRests, //    其他
					activity_id:vm.form.activityNo,
				};
				let data=[];
				if(vm.form.codeType==1){
					vm.form.prizeRuleData.forEach((item,index)=>{
						let obj={};
						obj.code_status=vm.form.codeType; //口令类型
						obj.fixed=item.codeWay; //口令类型 
						if(item.codeWay==1){
							obj.code=item.writeCode;  //手动填写
						}else{
							obj.code=item.csvUrl;   
						}
						obj.prize_id=item.id;  //奖品id
						obj.stock_number=item.restNum;  //库存
						data.push(obj);
					});
					body.code_rule=JSON.stringify(data);
				}else{
					vm.form.timeCodePrizeRuleData.forEach((item,index)=>{
						let obj={};
						obj.code_status=vm.form.codeType; //口令类型
						obj.start_time=vm.timeDateMinutes(item.startTime) ; //开始时间 
						obj.end_time=vm.timeDateMinutes(item.endTime); //结束时间 
						obj.code=item.code;  //口令
						obj.prize_id=item.id;  //奖品id
						obj.stock_number=item.restNum;  //库存	
						data.push(obj);
					});
					body.code_rule=JSON.stringify(data);
				}
				console.log(body);
				api.editGuessCodePrize(vm.form.activityNo,body).then(res=>{
					if(res.data.code==200){		
						//保存奖品
						if(vm.prizeSetReg()){
							vm.postPrizeSet();//保存奖品
						}
					}
				}).catch(function (err) {
					vm.fetchLoading=false;
                    vm.httpStatusCode(err);
					vm.$router.push({name:'activityList'});
				});
			},
			//保存奖品设置
			postPrizeSet(){
				let vm = this;
				// if(vm.form.codeType==1){
				// 	vm.postNum=vm.form.prizeRuleData.length;
				// }else{
				// 	vm.postNum=vm.form.timeCodePrizeRuleData.length;
				// }
				vm.postNum=1;
				if(vm.postNum>=1){
					let data={};
					data.activity_id=vm.form.activityNo;  //活动id
					if(vm.form.codeType==1){
						let item=vm.form.prizeRuleData[vm.postNum-1].list;
						data.available=parseInt(item.stock_number)-parseInt(vm.form.prizeRuleData[vm.postNum-1].restNum);
						data.img=item.background_image; //奖品图片
						data.max_amount='';
						data.prize={
							available:parseInt(item.stock_number)-parseInt(vm.form.prizeRuleData[vm.postNum-1].restNum),//剩余数量
							background_image:item.background_image, //奖品图片
							id:item.id, //奖品id
							name:item.name //奖品名称
						};
						data.prize_id=item.id; //奖品id
						data.stock_limit=vm.form.prizeRuleData[vm.postNum-1].restNum; //库存设置
						data.winning_limit=1; //中奖设置
						data.winning_probability=100
					}else{
						let item=vm.form.timeCodePrizeRuleData[vm.postNum-1].list;
						data.available=parseInt(item.stock_number)-parseInt(vm.form.timeCodePrizeRuleData[vm.postNum-1].restNum);
						data.img=item.background_image; //奖品图片
						data.max_amount='';
						data.prize={
							available:parseInt(item.stock_number)-parseInt(vm.form.timeCodePrizeRuleData[vm.postNum-1].restNum),//剩余数量
							background_image:item.background_image, //奖品图片
							id:item.id, //奖品id
							name:item.name //奖品名称
						};
						data.prize_id=item.id; //奖品id
						data.stock_limit=vm.form.timeCodePrizeRuleData[vm.postNum-1].restNum; //库存设置
						data.winning_limit=1; //中奖设置
						data.winning_probability=100
					}
					api.postPrizeNew1(vm.form.activityNo,data).then(res=>{
						if(res.data.code==200){
							vm.postNum--;
							if(vm.postNum<1){
								vm.postActivityPublishing();//保存活动拉新设置	
							}else{
								vm.postPrizeSet();  //自调
							}
						}
					}).catch(err=>{
						vm.fetchLoading=false;
						vm.httpStatusCode(err);
					})  
				}
			},

			//保存活动拉新设置  activityPublishing
			postActivityPublishing(){
				let vm = this;
				let wechatIsOpen; //是否开启微信分享
				let qr_code=[];
				if(vm.form.codeSwitch){
					wechatIsOpen='on';
					qr_code.push(vm.form.qrcode);
				}else{
					wechatIsOpen='off';
					qr_code=[];
				};
				let implantAppIsOpen;//是否开启app分享
				let app_urls=[];
				if(vm.form.implantApp){
					implantAppIsOpen='on';
					app_urls.push(vm.form.appDownloadUrl);
				}else{
					implantAppIsOpen='off';
					app_urls=[];
				};
				let body={
					app:{
						is_open:implantAppIsOpen,
						app_urls:app_urls
					},
					wechat:{
						is_open:wechatIsOpen,
						qr_code:qr_code
					}
				};
				api.activityPublishing(vm.form.activityNo,body).then(res=>{
					vm.fetchLoading=false;
					if(res.data.code==200){
						vm.$router.push({name:'activityList'});
						// vm.postActivityCommon();//保存所有信息
					}
				}).catch(function (err) {
					vm.fetchLoading=false;
                    vm.httpStatusCode(err);
					vm.$router.push({name:'activityList'});
				});
			},

			//内容设置验证
			contentSetReg(){
				if(this.form.activityName==''){
					this.$message({showClose: true,message: '活动名称不能为空'});
					return false;
				}else if(this.form.startTime==''){
					this.$message({showClose: true,message: '请选择活动开始时间'});
					return false;
				}else if(this.form.endTime==''){
					this.$message({showClose: true,message: '请选择活动结束时间'});
					return false;
				}else if(this.form.lotteryNum==''||this.form.lotteryNum<=0){
					this.$message({showClose: true,message: '抽奖次数必须大于0'});
					return false;
				}else{
					return true;
				}
			},
			//奖品验证
			prizeSetReg(){
				let vm = this;
				let num = /^\+?[1-9][0-9]*$/;　
				let flag;
				if(vm.form.codeType==1){
					vm.form.prizeRuleData.forEach((item,index)=>{
						if(item.codeWay==1){
							if(item.writeCode==''){
								vm.$message({showClose: true,message: '填写口令'});
								return flag=false;
							}else{
								flag=true;
							}
						}else if(item.codeWay==2){
							if(item.csvUrl==''){
								vm.$message({showClose: true,message: '请上传口令文件'});
								return flag=false;
							}else{
								flag=true;
							}
						}else if(item.id==''){
							vm.$message({showClose: true,message: '请选择奖品'});
							return flag=false;	
						}else if(item.availables<item.restNum){
							vm.$message({showClose: true,message: '填写库存不能大于可使用的库存'});
							return flag=false;	
						}else if(!num.test(item.restNum)||item.restNum<1){
							vm.$message({showClose: true,message: '库存为大于零的整数'});
							return flag=false;	
						}else{
							flag=true;	
						}
					});	
				}else{
					vm.form.timeCodePrizeRuleData.forEach((item,index)=>{
						if(item.startTime==''){
							vm.$message({showClose: true,message: '请选择开始时间'});
							return flag=false;	
						}else if(item.endTime==''){
							vm.$message({showClose: true,message: '请选择结束时间'});
							return flag=false;	
						}else if(index>0&&(item.startTime<vm.form.timeCodePrizeRuleData[index-1].endTime)){
							vm.$message({showClose: true,message: '同一时间段内不能出现两个时间'});
							return flag=false;	
						}else if(item.code==''){
							vm.$message({showClose: true,message: '请填写口令'});
							return flag=false;	
						}else if(item.id==''){
							vm.$message({showClose: true,message: '请选择奖品'});
							return flag=false;	
						}else if(item.availables<item.restNum){
							vm.$message({showClose: true,message: '填写库存不能大于可使用的库存'});
							return flag=false;	
						}else if(!num.test(item.restNum)||item.restNum<1){
							vm.$message({showClose: true,message: '库存为大于零的整数'});
							return flag=false;	
						}else{
							flag=true;	
						}
					});	
				}
				return flag;
			},
			//开通app验证
			appSetReg(){
				let vm = this;
				let reg=/^(https|http|ftp|rtsp|mms):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?$/;
				if(vm.form.implantApp){
					if(vm.form.appDownloadUrl==''||!reg.test(vm.form.appDownloadUrl)){
						this.$message({showClose: true,message: '请输入正确的APP下载链接'});
						return false;
					}else if(vm.form.listThumbnailIcon==''){
						this.$message({showClose: true,message: '列表缩略图不能为空'});
						return false;
					}else{
						return true;
					}
				}else{
					return true;
				}
			},
			//微信分享验证
			wxSetReg(){
				let vm = this;
				if(vm.form.shareSwitch){
					if(vm.form.shareIcon==''){
						this.$message({showClose: true,message: '分享图片不能为空'});
						return false;
					}else if(vm.form.shareTitle==''){
						this.$message({showClose: true,message: '分享标题不能为空'});
						return false;
					}else if(vm.form.shareContent==''){
						this.$message({showClose: true,message: '分享文案不能为空'});
						return false;
					}else{
						return true;
					}
				}else{
					return true;
				}
			},

			//获得奖品列表
			getAvailable(val=""){
				let vm = this;
				let body={
					per_page:vm.availableForm.per_page,
					page:vm.availableForm.page,   
					q:val
				};
				api.fetchAvailable(body).then(res=>{
					vm.prizeList=res.data.data.data;
					vm.availableForm.total=res.data.data.total;
					vm.availableForm.page=res.data.data.current_page;
					vm.availableForm.last_page=res.data.data.last_page;
				}).catch(err=>{
                    vm.httpStatusCode(err);
                }) ;
			},
			//搜索奖品列表
			searchPriceList(){
				this.getAvailable(this.availableForm.q);//获得奖品列表
			},
			//奖品分页
			pagePriceList(val){
				if(val==1&&this.availableForm.page>1){
					this.availableForm.page--;
					this.getAvailable(this.availableForm.q);//获得奖品列表
				}else if(val==2&&(this.availableForm.page>1&&this.availableForm.page<this.availableForm.last_page)){
					this.availableForm.page++;
					this.getAvailable(this.availableForm.q);//获得奖品列表
				}
			},
			//奖品分页
            selectPrize(a){
                this.availableForm.page=a;
				this.getAvailable();
            },
			//上传图片分页 点击当前的页数
            pageChange(a){
                this.updateImgcurrent_page=a;
            },
		    onEditorReady(editor) {
		        console.log('editor ready!', editor)
		    },
			//切换tabs
		    tabClickEvent(index){
				if(this.isTabContentShow){
					this.currentTab = index;
				}else{
					this.currentTab = 0;
					this.$message({
			          showClose: true,
			          message: '请先保存内容设置'
			        });
				}
			},
			addSpecialRule(){
				var prizeLength = this.pickedPrizeList.length;
				if (prizeLength === 0) {
					this.$message({
			          showClose: true,
			          message: '请先添加奖品,然后再设置特殊规则'
			        });
				} else {
					var obj = {
						startTime: '',
						endTime: '',
						prizeOptionValue: 0,
						prizeNum: '0'
					}
					this.specialRuleData.push(obj);
				}
			},
			// 固定口令删除奖品
			deletePrizeRule(index,item){
				Vue.delete(this.form.prizeRuleData, index);
				this.prizeList.push(item);
			},
			showAddPrizeToast(index,val){
				this.addPrizeBox = true;
				this.currentAddPrizeIndex = index; //下标记
			},
			hideAddPrizeToast(){
				this.addPrizeBox = false;
			},
			//选取奖品
			pickPrize(item,index){
				this.addPrizeBox = false;
				var type = this.form.codeType;
				var index = this.currentAddPrizeIndex;
				if (type == 1) {  //固定口令
					var arr = this.form.prizeRuleData;
					arr[index].prize = item.name;
					arr[index].id = item.id;
					arr[index].availables = item.availables;
					arr[index].list=item;
					this.prizeRuleData = arr;
				} else {  //定时口令
					var arr = this.form.timeCodePrizeRuleData;
					arr[index].prize = item.name;
					arr[index].id = item.id;
					arr[index].availables = item.availables;
					arr[index].list=item;
					this.timeCodePrizeRuleData = arr;
				}
			},
			// 添加固定口令奖品列表
			addPrizeRule(){
				var obj = {
					codeWay: '1',
					writeCode:'', //手动填写口令
					code: '',
					csvFile: '',
					csvUrl:'',
					prize: '',  //活动名称
					id:'',		//活动id
					availables:'', //可用库存
					restNum: 1,
					list:''  //活动活动列表
				};
				this.form.prizeRuleData.push(obj);
			},
			// 添加定时口令奖品列表
			addTimeCode(){
				var that = this;
				var index = that.form.timeCodePrizeRuleData.length;
				if (index === 3) {
					that.$message({
                      showClose: true,
                      type: 'error',
                      message: '最多可以添加3个时段'
                    });
                    return;
				}
				that.form.timeCodePrizeRuleData.push({
					startTime: '',
					endTime: '',
					code: '',
					prize: '',  //活动名称
					id:'',		//活动id
					availables:'', //可用库存
					restNum: 1,
					list:''  //活动活动列表
				});
			},
			// 删除定时口令奖品
			deleteTimeCodePrizeRule(index,item){
				if(this.form.timeCodePrizeRuleData.length>1){
					Vue.delete(this.form.timeCodePrizeRuleData, index);
					this.prizeList.push(item);
				}else{
					this.$message({message: '至少保留一个奖品'});
				}
			},
			//打开上传图片box
			showUploadPicToast(val){
				this.uploadImgBoxIndex=val;
				this.uploadPicBox = true;
			},
			hideUploadPicToast(){
				this.uploadPicBox = false;
				this.currentBannerIndex = -1;
			},
			chooseBannerImg(index){
				this.currentBannerIndex = index;
			},
			// 上传图片点击确定
			comfirmBannerImg(){
				var curIndex = this.currentBannerIndex;
				if (curIndex === -1) {
					this.$message({
			          showClose: true,
			          message: '请先选择图片'
			        });
				} else if (this.uploadImgBoxIndex ==1) {
					this.form.bgImg = this.uploadPicList[curIndex].src;
					this.hideUploadPicToast();
				} else if (this.uploadImgBoxIndex ==2) {
					this.form.qrcode = this.uploadPicList[curIndex].src;
					this.hideUploadPicToast();
				}else if (this.uploadImgBoxIndex ==3) {
					this.form.shareIcon = this.uploadPicList[curIndex].src;
					this.hideUploadPicToast();
				}
			},
			cancelBg(val){
				if (val==1) {
					this.form.bgImg = '';
				} else if (val==2) {
					this.form.qrcode = '';
				} else if(val==3){
					this.form.shareIcon = '';
				}else{
					this.form.listThumbnailIcon='';	
				}
			},
			// 上传随机口令文件
			addCsv(event, index){
				let vm = this;
				let ext=e.target.value.toLowerCase().split('.').splice(-1);
				if ("csv" != ext) {  
					vm.$message({  message: '只能上传csv文件'});
					return false;  
				}else{
					let form = new FormData();  
        			form.append('upfile', e.target.files[0]);
					api.uploadPrizeImg(form).then(res=>{
						if(res.data.code==0){
							vm.form.prizeRuleData[index].csvFile =e.target.files[0].name;
							vm.form.prizeRuleData[index].csvUrl=res.data.result;
							vm.$message({ message: '上传成功', type: 'success' });
						}
					});	
				} 
	            
			},
			addImgEvent(event){
				var that = this;
				that.imgUpLoading=true;
	            var img1 = event.target.files[0];
	            //生成临时图片路径
                var temSrc = URL.createObjectURL(img1);
                //判断图片尺寸大小
	            var size = img1.size/1024;
	            //小于100k
	            if(size>200){
					that.imgUpLoading=false;
            		that.$message({
                      showClose: true,
                      type: 'error',
                      message: '图片大小不能大于200KB'
                    }); 
	                return false;  
	            };
	            //判断图片像素尺寸
        		var _img = new Image();
        		_img.onload = function  () {
        			var imgWidth = _img.width,
        				imgHeight = _img.height;
						console.log(imgWidth);
						console.log(imgHeight);
        			if (that.uploadImgBoxIndex == 1) {
	        			if (imgWidth!=640 || imgHeight!=1200) {
							that.imgUpLoading=false;
		            		that.$message({
		                      showClose: true,
		                      type: 'error',
		                      message: '请上传尺寸为640*1200的图片'
		                    }); 
			                return false;
	        			};
						//上传背景图
						let formdata = new FormData();
				        formdata.append('upfile', img1);
				        api.uploadPrizeImg(formdata).then(res => {
							that.$message({
								message: '上传成功',
								type: 'success'
							});
							that.hideUploadPicToast();
							that.imgUpLoading=false;
				        	that.form.bgImg= res.data.result;
				        }).catch(err=>{
							that.httpStatusCode(err);
							that.hideUploadPicToast();
							that.imgUpLoading=false;
						}) 
        			}else if(that.uploadImgBoxIndex == 2) {
        				if (imgWidth!=imgHeight) {
							that.imgUpLoading=false;
		            		that.$message({
		                      showClose: true,
		                      type: 'error',
		                      message: '请上传比例为1:1的图片'
		                    }); 
			                return false;
	        			};
						//上传二维码
						let formdata = new FormData();
				        formdata.append('upfile', img1);
				        api.uploadPrizeImg(formdata).then(res => {
							that.$message({
								message: '上传成功',
								type: 'success'
							});
							that.hideUploadPicToast();
							that.imgUpLoading=false;
				        	that.form.qrcode = res.data.result;
				        }).catch(err=>{
							that.httpStatusCode(err);
							that.hideUploadPicToast();
							that.imgUpLoading=false;
						})  
        			}else if(that.uploadImgBoxIndex == 3) {
        				if (imgWidth!=imgHeight) {
							that.imgUpLoading=false;
		            		that.$message({
		                      showClose: true,
		                      type: 'error',
		                      message: '请上传比例为1:1的图片'
		                    }); 
			                return false;
	        			};
						//上传分享图片
						let formdata = new FormData();
				        formdata.append('upfile', img1);
				        api.uploadPrizeImg(formdata).then(res => {
							that.$message({
								message: '上传成功',
								type: 'success'
							});
							that.hideUploadPicToast();
							that.imgUpLoading=false;
				        	that.form.shareIcon = res.data.result;
				        }).catch(err=>{
							that.httpStatusCode(err);
							that.hideUploadPicToast();
							that.imgUpLoading=false;
						})  
        			}else if(that.uploadImgBoxIndex == 4) {
        				if (imgWidth!=imgHeight) {
							that.imgUpLoading=false;
		            		that.$message({
		                      showClose: true,
		                      type: 'error',
		                      message: '请上传比例为1:1的图片'
		                    }); 
			                return false;
	        			};
						//上传分享图片
						let formdata = new FormData();
				        formdata.append('upfile', img1);
				        api.uploadPrizeImg(formdata).then(res => {
							that.$message({
								message: '上传成功',
								type: 'success'
							});
							that.hideUploadPicToast();
							that.imgUpLoading=false;
				        	that.form.listThumbnailIcon = res.data.result;
				        }).catch(err=>{
							that.httpStatusCode(err);
							that.hideUploadPicToast();
							that.imgUpLoading=false;
						})  
        			}
        			
			        that.hideUploadPicToast();
					setTimeout(function  () {
			        	URL.revokeObjectURL(temSrc);
			        },100);
        		}
        		_img.src = temSrc;
				event.target.value='';
			},
        },
		beforeRouteEnter:function(to,from,next) {    //路由生命周期
			next(vm => {
				if(vm.$route.query.tplModelId){
					// vm.form.bgImg=baseImgPath+vm.$route.query.background;
					vm.defaultBg=baseImgPath+vm.$route.query.background;
					vm.form.tplModelId=vm.$route.query.tplModelId;
					vm.form.model_id=vm.$route.query.model_id;
				}else{
					vm.$router.go(-1);
				}
			})
		},
	}
</script>
<style>
	/* 修改输入框样式 */
	.pick-date-box .el-input__inner{
		height: 34px;
		box-sizing: border-box;
		border-radius: 0;
		background-color: #f4f8fb;
	    color: #888;
	    border: 1px solid #efefef;
	    box-shadow: none;
	    font-size: 12px;
	    width: 100%;
        height: 34px;
        padding: 6px 12px;
        box-sizing: border-box;
	}
	.special-item .el-input__inner{
		height: 32px;
		box-sizing: border-box;
		border-radius: 0;
		background-color: #f4f8fb;
	    color: #888;
	    border: 1px solid #efefef;
	    box-shadow: none;
	    font-size: 12px;
	    width: 109px;
        padding: 6px 12px;
        box-sizing: border-box;
	}
	.special-item .el-date-editor i{
		display: none;
	}
	.special-item .el-select .el-input__inner{
		padding-right: 25px;
		width:130px;
	}
	.lotteryNum-box .el-input__inner{
		width:142px;
		box-sizing: border-box;
		border-radius: 0;
		height: 34px;
		font-size: 12px;
	    color: rgb(136, 136, 136);
	    border-color: rgb(239, 239, 239);
	    background-color: rgb(238, 238, 238);
	}
	.tag-box .el-input__inner{
		width:160px;
	}
	.tag-box .el-input{
	}
	.rule-box .ql-container{
		height: 300px;
		background: #f4f8fb;
	}
	.share-switch .el-switch{
		position: relative;
		top:-1px;
	}
	.rule-title .el-switch{
		top:-1px;
		left: 10px;
	}
	.el-switch__label span{
		color:rgba(0,0,0,0);
	}
	#add-prize-box .el-input {
	    width: 260px;
	}
	.el-radio-group .el-radio{
		font-size: 12px;
	}
	.code-type-radio .el-radio__label,.prize-list .el-radio__label{
		font-size: 12px;
	}
	.code-type-radio .el-radio__inner,.prize-list .el-radio__inner{
		width:14px;
		height: 14px;
	}
	._prize-list .el-input__inner{
		height: 30px;
		box-sizing: border-box;
		border-radius: 0;
		background-color: #f4f8fb;
	    color: #888;
	    border: 0;
	    box-shadow: none;
	    font-size: 12px;
	    width: 100%;
	    display: block;
	}
	._prize-list .el-date-editor i{
		display: none;
	}
	._prize-list .el-input__icon+.el-input__inner{
		padding-right: 0;
	}
	.text-hit{
    text-align: center;
    padding:20px;
    color:#666;
	}
	.set-bottom{
		text-align: center;
		margin-top:40px;
	}
	.save-btn{
		width: 150px;
		line-height: 34px;
		border-radius: 3px;
		padding: 0;
		color: #fff;
		font-size: 12px;
		background-color: #ec5463;
		height: 34px;
		font-weight: 400;
		text-align: center;
		cursor: pointer;

	}
</style>
<style lang="less" scoped>
	@import '../style/setTemplate_code';

</style>